<template>
  <div class="task-wrapper" :style="{ 'height': documentClientHeight + 'px' }">
    <div class="left">
      <Menu ref="menuRef" @addOrUpdateTaskHandle="addOrUpdateTaskHandle" @selectMenu="selectTab" :menuList="menuList" :title="'创建任务'"></Menu>
    </div>
    <AddOrUpdateTask ref="AddOrUpdateTask" @refresh="refreshTask($event)"></AddOrUpdateTask>
    <TaskDetail ref="TaskDetail" @closeSelf="hideTaskDetail" @refresh="refreshTask" :taskDetailVisible.sync="taskDetailVisible"></TaskDetail>
    <div class="right">
      <div class="content-header">
        <span>{{menuList[currentMenuIndex-1].name}}</span>
        <el-popover
          placement="bottom"
          title="筛选"
          width="330"
          trigger="click">
          <el-form label-width="80px" class="filter-form">
            <el-form-item label="项目">
              <el-select :multiple="true" :filterable="true" v-model="form.projectIds" placeholder="请选择项目" style="width: 100%;">
                <el-option style="width: 200px;" v-for="item in projectArr" :key="item.id" :label="item.taskName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="任务名称">
              <el-input placeholder="请输入任务名称" v-model="form.taskName"></el-input>
            </el-form-item>
            <el-form-item label="负责人">
              <div @click="selectDingUsers('plateProjectManagerIdArr','plateProjectManagerName','plateProjectManagerId', 'plateProjectAvator', 'plateProjectManagerNameArr')" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
              <div class="select-btn" v-for="(member, idx) in form.plateProjectManagerNameArr" :key="member" style="padding: 0;">{{member}}
                <div class="del" @click="delMember(idx)">移除</div>
              </div>
            </el-form-item>
            <el-form-item label="计划截止">
              <el-row>
                <el-date-picker v-model="form.filterStartPlanFinishTime" type="date" placeholder="任务计划结束起始日期" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
              </el-row>
              <el-row style="text-align: center;">至</el-row>
              <el-row>
                <el-date-picker v-model="form.filterEndPlanFinishTime" type="date" placeholder="任务计划结束截止日期" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getTaskList(true)">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
          <span class="filter" slot="reference">
            <img src="../../../assets/livolobim/filter.png">
            <div class="dot" v-if="hasSearchCondition"></div>
          </span>
        </el-popover>
      </div>
      <div class="content-wrapper">
        <div v-if="currentMenuIndex < 5">
          <div class="content-tab-bar" 
          v-for="value in subMenuList"
          :key="value.id"
          :value="value">
            <div class="tab-item" @click="selectTab(currentMenuIndex, value.index)" :class="{'active': currentIndex === value.index}">{{value.name}}</div>
          </div>
        </div>
        <div v-if="currentMenuIndex === 5 || currentMenuIndex === 6 || currentMenuIndex === 7">
          <div class="content-tab-bar"
            v-for="value in subMenuListAll"
            :key="value.id"
            :value="value">
            <div class="tab-item" @click="selectTab(currentMenuIndex, value.index)" :class="{'active': currentIndex === value.index}">{{value.name}}</div>
          </div>
        </div>
        <div v-if="currentMenuIndex === 8">
          <div class="content-tab-bar"
            v-for="value in todayFinishedMenuList"
            :key="value.id"
            :value="value">
            <div class="tab-item" @click="selectTab(currentMenuIndex, value.index)" :class="{'active': currentIndex === value.index}">{{value.name}}</div>
          </div>
        </div>
        <div class="content" v-infinite-scroll="loadData" infinite-scroll-disabled="disabled" infinite-scroll-immediate="false">
          <div class="task-component" v-for="value in taskList" :key="value.id" :value="value">
            <div class="task-item" @click="openTaskDetail(value.id)">
              <span class="arrow-status" :class="getArrowType(value)"></span>
              <span class="task-status">{{getWord(value)}}</span>
              <div class="top">
                <div class="logo">
                  <img :src="value.taskUrl? 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/'+value.taskUrl : 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/icon%20blue-1.png'"  style="width: 48px; height: 48px;border-radius: 5px;">
                </div>
                <div class="task-info">
                  <p class="task-name">{{value.taskName}}</p>
                  <p class="project"><span>{{value.taskBelongName}}</span></p>
                </div>
              </div>
              <div class="bottom">
                <p><i class="el-icon-user"></i>{{value.taskPrincipalName}}</p>
                <p><i v-if="value.taskRealEndtime || analyzeData2(value)" class="el-icon-bell"></i><span v-if="value.taskRealEndtime" style="margin-right: 15px;">{{value.taskRealEndtime}}</span><span :class="'delayColor'" v-if="analyzeData2(value)" :style="{'color': analyzeData2(value).indexOf('提前')>= 0 ? '#21D779': '#FF5050'}">（{{analyzeData2(value)}}）</span></p>
              </div>
            </div>
          </div>
          <img v-if="taskList.length === 0 && !isFirstLoading" style="width:200px;margin: auto;position:absolute;top:0;right:0;left:0;bottom: 0;" src="../../../assets/livolobim/empty.png" alt="">
        </div>
      </div>
      <div style="text-align: center;margin-top: 8px;color: #909399;">共有{{totalCount}}个任务</div>
    </div>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from "@/utils/formUtil";
import Menu from './component/Menu'
import AddOrUpdateTask from './add-or-update-task'
import TaskDetail from './task-detail'
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      headers: {
        token: this.$cookie.get('token')
      },
      documentClientHeight: '',
      currentMenuIndex: 1,  //menuList当前所选
      currentIndex: 1,      //每个菜单下的子菜单
      addOrUpdateVisible: false,  //新增或者编辑任务弹框是否打开
      taskDetailVisible: false,   //打开任务详情页
      dialogVisible: false,
      arrowType:'',
      menuList: [{
        index: 1,
        icon: 'el-icon-folder-opened',
        isFolder: true,
        name: '我的任务'
      },{
        index: 2,
        name: '今日任务'
      },{
        index: 3,
        name: '最近7天'
      },{
        index: 4,
        name: '最近30天'
      },{
        index: 5,
        icon: 'el-icon-star-off',
        isFolder: true,
        name: '关注的任务'
      },{
        index: 6,
        icon: 'el-icon-folder',
        isFolder: true,
        name: '全部任务'
      },{
        index: 7,
        name: '今日新增'
      },{
        index: 8,
        name: '今日完成'
      }],
      subMenuList: [{
        index: 1,
        name: '全部',
      },{
        index: 2,
        name: '待我完成',
      },{
        index: 3,
        name: '待我确认',
      },{
        index: 4,
        name: '我完成的',
      },{
        index: 5,
        name: '我确认的',
      },{
        index: 6,
        name: '我创建的',
      }],
      subMenuListAll: [{
        index: 1,
        name: '全部'
      },{
        index: 2,
        name: '待完成'
      },{
        index: 3,
        name: '待确认'
      },{
        index: 4,
        name: '已完成'
      },{
        index: 5,
        name: '已终止'
      }],
      todayFinishedMenuList: [{
        index: 1,
        name: '全部'
      },{
        index: 2,
        name: '提前完成'
      },{
        index: 3,
        name: '按时完成'
      },{
        index: 4,
        name: '逾期完成'
      }],
      taskList: [],
      isFirstLoading: true,
      loading: false,
      page: 1,
      limit: 30,
      totalPage: 1,
      totalCount: 0,
      form: {
        plateProjectManagerId: '',
        plateProjectManagerName: '',
        plateProjectAvator: [],
        plateProjectManagerNameArr: [],
        plateProjectManagerIdArr: [],
        taskName: '',
        projectIds: [],
        filterStartPlanFinishTime: null,
        filterEndPlanFinishTime: null,
      },
      formInit: {},
      projectArr: []
    }
  },
  mixins: [dingMixin],
  components: {
    Menu, AddOrUpdateTask, TaskDetail
  },
  computed: {
    disabled () {
      return this.isFirstLoading || this.loading || this.noMore
    },
    noMore () {
      return this.page >= this.totalPage;
    },
    isManager() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1260854998536855554')
    },
    hasSearchCondition() {
      return JSON.stringify(this.form) !== this.formInit
    },
  },
  methods:{
    resetForm() {
      this.form = JSON.parse(this.formInit)
      this.getTaskList(true)
    },
    async getProjectList() {
      let projectResult = await this.$httpN.postB('division/task/filterProjectList', {searchType: 3, limit: 999});
      this.projectArr = projectResult.list;
    },
    selectDingUsers(ids, name, idsStr, avator, names){
      this.complexPicker(300, [], this.form[ids]).then((data)=>{
        this.form[ids] = data.map(item => item.emplId);
        this.form[avator] = data.map(item => item.avatar)
        this.form[names] = data.map(item => item.name)
        this.form[name] = this.form[names].join(',');
        this.form[idsStr] = this.form[ids].join(',')
      })
    },
    delMember(idx) {
      this.form.plateProjectAvator.splice(idx,1); 
      this.form.plateProjectManagerNameArr.splice(idx,1); 
      this.form.plateProjectManagerIdArr.splice(idx,1); 
      this.form.plateProjectManagerId = this.form.plateProjectManagerIdArr.join(',')
      this.form.plateProjectManagerName = this.form.plateProjectManagerNameArr.join(',')
    },
    getWord(item) {
      if(item.taskStatus === '1') {
        return new Date(dateUtil.thisDay()).getTime() >= new Date(item.taskStartTime).getTime()? '进行中': '未开始'
      }else if(item.taskStatus === '9') {
        return '已终止'
      }else if(item.taskStatus === '2') {
        return '待确认'
      }else if(item.taskStatus === '3') {
        if(new Date(item.taskRealEndtime).getTime() > new Date(item.taskEndTime).getTime()) {
          return '逾期完成'
        }else if(new Date(item.taskRealEndtime).getTime() === new Date(item.taskEndTime).getTime()){
          return '按时完成'
        }else{
          return '提前完成'
        }
      }
    },
    getArrowType(item) {
      if(item.taskStatus === '1') {
        return new Date(dateUtil.thisDay()) >= new Date(item.taskStartTime).getTime()? 'arrow-4': 'arrow-2'
      }else if(item.taskStatus === '9') {
        return 'arrow-3'
      }else if(item.taskStatus === '2') {
        return 'arrow-6'
      }else if(item.taskStatus === '3') {
        if(new Date(item.taskRealEndtime).getTime() > new Date(item.taskEndTime).getTime()) {
          return 'arrow-5'
        } else{
          return 'arrow-1'
        }
      }
    },
    async refreshTask() {
      await this.getTaskList(true);
    },
    async selectTab(currentMenuIndex, currentSubMenu) {
      this.currentIndex = currentSubMenu;
      if (currentMenuIndex !== this.currentMenuIndex){
        this.currentMenuIndex = currentMenuIndex;
      }
      formUtil.resetData(this.form);
      await this.getTaskList(true);
    },
    async getTaskList(init) {
      if(init) {
        this.page = 1;
        this.taskList = [];
        this.isFirstLoading = true;
      }
      let searchObj = {
        filterSectionType: this.currentMenuIndex < 5 ? 1 : this.currentMenuIndex === 5 ? 2 : 3,
        sectionType: this.currentMenuIndex < 5 ? this.currentMenuIndex : this.currentMenuIndex === 5 ? 1 : this.currentMenuIndex - 5,
        searchType: this.currentIndex,
        filterPrincipalIds: this.form.plateProjectManagerId,
        taskName: this.form.taskName,
        projectIds: this.form.projectIds.join(','),
        filterStartPlanFinishTime: this.form.filterStartPlanFinishTime,
        filterEndPlanFinishTime: this.form.filterEndPlanFinishTime,
        page: this.page,
        limit: this.limit
      }
      let result = await this.$httpN.postB('division/task/filterTaskList',searchObj);
      
      this.loading = false;
      this.taskList.push(...result.list);

      if(init) {
        this.totalPage = result.totalPage;
        this.totalCount = result.totalCount;
        this.$nextTick(() => {
          this.isFirstLoading = false;
        })
      }
    },

    analyzeData2(item) {
      if(item.taskStatus === '1') {
        if(new Date(dateUtil.thisDay()) < new Date(item.taskStartTime).getTime()){
          return ''
        }else {
          if(new Date(dateUtil.thisDay()) > new Date(item.taskEndTime).getTime()) {
            let time = this.daysDiff(dateUtil.thisDay(), item.taskEndTime);
            return `逾期${time}天`
          }else {
            let time = this.daysDiff(dateUtil.thisDay(), item.taskEndTime) + 1;
            return `剩余${time}天`
          }
        }
      }else if(item.taskStatus === '9') {
        return ''
      }else if(item.taskStatus === '2') {
        if(new Date(dateUtil.thisDay()) > new Date(item.taskEndTime).getTime()) {
          let time = this.daysDiff(dateUtil.thisDay(), item.taskEndTime);
          return `逾期${time}天`
        }else {
          let time = this.daysDiff(dateUtil.thisDay(), item.taskEndTime) + 1;
          return `剩余${time}天`
        }
      }else if(item.taskStatus === '3') {
        if(new Date(item.taskRealEndtime).getTime() > new Date(item.taskEndTime).getTime()) {
          let time = this.daysDiff(item.taskRealEndtime, item.taskEndTime);
          return `逾期${time}天`
        }else if(new Date(item.taskRealEndtime).getTime() === new Date(item.taskEndTime).getTime()){
          let time = this.daysDiff(item.taskRealEndtime, item.taskEndTime);
          return ''
        }else{
          let time = this.daysDiff(item.taskRealEndtime, item.taskEndTime);
          return `提前${time}天`
        }
      }
    },
    hideTaskDetail() {
      this.taskDetailVisible = false;
    },
    // 打开任务详情页
    async openTaskDetail(id) {
      this.taskDetailVisible = true;
      this.$nextTick(() => {
        this.$refs.TaskDetail.init(id);
      })
    },
    // 计算两个日期的时间差
    daysDiff(oDate1,oDate2){
      let  aDate, iDays;
      oDate1 = new Date(oDate1);
      oDate2 = new Date(oDate2);
      iDays = parseInt((oDate1 - oDate2) / 1000 / 60 / 60 /24);
      return Math.abs(iDays)
    },
    //新增或编辑任务、子任务
    addOrUpdateTaskHandle(){
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.AddOrUpdateTask.init({taskDatatype: 2});
      })
    },
    async loadData() {
      this.loading = true;
      this.page ++;
      await this.getTaskList();
    }
  },
  async mounted() {
    this.documentClientHeight = document.documentElement['clientHeight'] - 50
    window.onresize = () => {
      this.documentClientHeight = document.documentElement['clientHeight'] - 50
    }
    this.formInit = JSON.stringify(this.form)
    if(this.$route.params.taskId) {
      this.currentIndex = 1;
      this.currentMenuIndex = 6;
      this.$refs.menuRef.currentIndex = 6;
      await this.openTaskDetail(this.$route.params.taskId)
    }else {
      this.currentMenuIndex = 2;
      this.$refs.menuRef.currentIndex = 2;
    }
    await this.getTaskList(true);
    this.getProjectList()
    // if(this.isManager) {
    //   this.menuList.push({
    //     index: 9,
    //     icon: 'el-icon-search',
    //     isFolder: true,
    //     name: '自定义'
    //   })
    // }
  }
}
</script>

<style lang="scss" scoped>
  .content-wrapper .content::-webkit-scrollbar {/*滚动条整体样式*/
    width: 0px;     /*高宽分别对应横竖滚动条的尺寸*/
    height: 0px;
    scrollbar-arrow-color:red;
  }
  .task-wrapper{
    display:flex;
    .left{
      width: 250px;
      height: 100%;
      z-index: 1;
      background: #FFF;
      box-shadow: 3px 0 4px #F0F0F0;
    }
    .right{
      flex:1;
      .content-header{
        line-height: 50px;
        background: #FFF;
        font-size: 16px;
        font-weight: bold;
        padding: 0 25px;
        box-shadow: 0 3px 4px #F0F0F0;
        display: flex;
        justify-content:space-between;
        .filter {
          height: 50px;
          position: relative;
          > img {
            width: 24px;
            height: 24px;
            cursor: pointer;
            position: relative;
          }
          .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #4983FF;
            display: inline-block;
            vertical-align: super;
          }
        }
      }
      .content-wrapper{
        height: calc(100% - 80px);
        padding: 20px;
        .content-tab-bar{
          display: inline-block;
          >div{
            padding: 0 15px;
            margin-right: 10px;
            background: #ECECEC;
            line-height: 40px;
            text-align: center;
            color: #999CA1;
            border-radius: 5px 5px 0 0;
            cursor: pointer;
            span{
              padding: 0 6px;
              margin-left: 4px;
              background: #DBDBDC;
              border-radius: 8px;
              font-size: 12px;
            }
          }
          .active{
            box-shadow: 1px -1px 2px rgb(221, 221, 221);
            background: #FFF;
            color:#4983FF;
            font-weight: bold;
            span{
              background: #E4EDFF;
            }
          }
        }
        .content{
          z-index: 2;
          height: calc(100% - 20px);
          box-shadow: 4px 4px 4px rgb(221, 221, 221);
          overflow-y: auto;
          background: white;
          padding: 10px;
          position: relative;
          .task-component{
            padding: 20px;
            float:left;
            width: 25%;
            .task-item{
              width: 100%;
              height: 155px;
              border: 1px solid #D3E3E8;
              background: white;
              border-radius: 5px;
              box-shadow: 0px 0px 1px rgb(221, 221, 221);
              padding: 30px 45px;
              cursor: pointer;
              position: relative;
              &:hover{
                box-shadow: 0px 0px 4px rgb(221, 221, 221);
              }
              .arrow-status{
                width:0;
                height:0;
                position: absolute;
                top: 0;
                left: 0;
                border-top-left-radius: 5px;
                border-top:solid 30px #4495FF;
                border-left:solid 30px #4495FF ;
                border-bottom:solid 30px transparent;
                border-right:solid 30px transparent;
                &.arrow-1{
                  border-top:solid 30px #21D779;
                  border-left:solid 30px #21D779 ;
                }
                &.arrow-2{
                  border-top:solid 30px #9987FA;
                  border-left:solid 30px #9987FA ;
                }
                &.arrow-3{
                  border-top:solid 30px #DBDADA;
                  border-left:solid 30px #DBDADA ;
                }
                &.arrow-4{
                  border-top:solid 30px #4495FF;
                  border-left:solid 30px #4495FF ;
                }
                &.arrow-5{
                  border-top:solid 30px #B0C7CD;
                  border-left:solid 30px #B0C7CD ;
                }
                &.arrow-6{
                  border-top:solid 30px #E6A23C;
                  border-left:solid 30px #E6A23C ;
                }
              }
              .task-status{
                position: absolute;
                width: 60px;
                line-height: 20px;
                left: -6px;
                top: 11px;
                color: white;
                font-size: 12px;
                transform: rotate(-45deg);
                text-align: center;
                font-weight: normal;
              }
              &::after{
                content: '';
                width:0;
                height:0;
                position: absolute;
                top: 0;
                left: 0;
                border-top-left-radius: 5px;
                border-top:solid 15px white;
                border-left:solid 15px white ;
                border-bottom:solid 15px transparent;
                border-right:solid 15px transparent;
              }
              .top{
                display:flex;
                .logo{
                  width: 48px;
                  height: 48px;
                  text-align: center;
                  background: #409EFF;
                  text-align: center;
                  border-radius: 4px;
                  i{
                    color: white;
                    font-size: 30px;
                    line-height: 48px;
                  }
                }
                .task-info{
                  width: calc(100% - 58px);
                  p{
                    margin: 0;
                    padding-left:10px;
                  }
                  .task-name {
                    text-overflow: -o-ellipsis-lastline;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    line-clamp: 1;
                    -webkit-box-orient: vertical;
                  }
                  .project{
                    width: 100%;
                    margin-top: 15px;
                    span{
                      background: #FFDCDC;
                      color: #FF5050;
                      padding: 2px 6px;
                      border-radius: 3px;
                      max-width: 100%;
                      display: inline-block;
                      overflow: hidden;
                      text-overflow:ellipsis;
                      white-space: nowrap;
                    }
                  }
                }
              }
              .bottom{
                margin-top: 10px;
                p{
                  margin: 5px 0 0 0 ;
                  color: #79828C;
                  i{
                    margin-right: 5px;
                  }
                }
                .task-status{
                  position: absolute;
                  right: 10px;
                  top: 15px;
                  line-height: 30px;
                  width: 80px;
                  text-align: center;
                  color:white;
                  border-radius: 20px;
                }
              }
              .normalBg{
                background: #409EFF;
              }
              .warningBg{
                background: #E6A23C;
              }
              .successBg{
                background: #67C23A;
              }
              .delayColor{
                color: #F56C6C;
              }
            }
          }
        }
      }
    }
  }

  @media screen and (max-width: 1600px) {
    .task-wrapper .right .content-wrapper .content .task-component {
      width: 33.3%;
    }
  }

  @media screen and (max-width: 1300px) {
    .task-wrapper .right .content-wrapper .content .task-component {
      width: 50%;
    }
  }
  .select-btn{
    position: relative;
    float:left;
    font-weight: normal;
    margin-right: 5px;
    margin-bottom: 10px;
    width: 80px;
    height: 28px;
    border-radius: 30px;
    background: #FAFAFA;
    border: 1px solid #ECECEC;
    position: relative;
    padding-left: 21px;
    line-height: 28px;
    color: #7982A7;
    font-size: 12px;
    text-align: center;
    cursor: pointer;
    span{
      position: absolute;
      top: 1px;
      left: 1px;
      display:block;
      height: 24px;
      width: 24px;
      background: #CACACA;
      color: white;
      border-radius: 50%;
      text-align: center;
      line-height: 24px;
      img{
        width: 24px;
        height: 24px;
        border-radius: 50%;
      }
    }
    .del{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 30px;
      color: white;
      text-align: center;
      background:rgba(130, 130, 130, 0.9);
      display: none;
    }
    &:hover{
      .del{
        display: block;
      }
    }
  }
</style>